import { Portal, Toast } from '@ant-design/react-native';
import LoadingUtil from './LoadingUtil';

const ServerBaseUrl = 'http://web.ydctech.org/mgr/api'; // 'http://web.vitalitylife.cn/mgr/api';//http://120.78.168.168:8999/mgr/api';
export const GoodsImgUrl = ServerBaseUrl + '/img/commodity/head/'; // 商品图片链接,后面拼'{商品id}_1.{接口返回的pic_url,其实是后缀}'(1代表请求原图，2代表请求缩略图)
export const PromptImgUrl = ServerBaseUrl + '/img/commodity/prompt/'; // 使用须知图片链接,参数同上面
export const AdImgUrl = ServerBaseUrl + '/img/ad/head/'; // 广告图片链接,参数同上面
export const AdContentImgUrl = ServerBaseUrl + '/img/ad/content/'; // 广告内容图片链接,参数同上面
export const CardPwdImgUrl = ServerBaseUrl + '/img/card/content/'; // 卡券图片链接,参数同上面
export const UserHeadImgUrl = ServerBaseUrl + '/img/customer/avatar/'; // 客户头像图片链接,参数同上面
export const oncePageNum = 20;

export function httpGet(uri) {
  LoadingUtil.showLoading();
  // uri = ServerBaseUrl + uri;
  const options = {
    method: 'GET',
    credentials: 'include',
    headers: { Accept: 'application/json', 'Content-Type': 'application/json' }
  };
  console.log('===请求参数==uri==>' + uri);
  return new Promise((resolve, reject) => {
    fetch(uri, options)
      .then(response => {
        if (response.ok) {
          return response.json();
        } else {
          reject({ status: response.status, msg: response.statusText });
        }
      })
      .then(data => {
        console.log('==============api===data====>' + JSON.stringify(data));
        LoadingUtil.dismissLoading();
        if (0 == data.errorCode) {
          resolve(data.body);
        } else {
          Toast.fail(data.errMsg ? data.errMsg : '抱歉,加载异常,请重试!');
        }
      })
      .catch(ex => {
        reject({ status: -1, error: ex });
        LoadingUtil.dismissLoading();
        console.log(' ==============api==err=====> ' + JSON.stringify(ex));
      });
  });
}

export function httpPost(uri, params, curPageNum) {
  const loadingKey = Toast.loading('卖力加载中...');
  uri = ServerBaseUrl + uri;
  if (curPageNum >= 1) {
    params.append('offset', (curPageNum - 1) * oncePageNum);
    params.append('limit', oncePageNum);
  } // end of if
  const userInfoObj = null; // menuSideBar.getLoginUserInfo();
  if (userInfoObj) params.append('accessToken', userInfoObj.token);
  const init = { method: 'POST', credentials: 'include', body: params };
  const paramEntity = params.entries();
  let item = null;
  let paramStr = '';
  while ((item = paramEntity.next())) {
    if (item.done) break;
    paramStr += item.value[0] + ':' + item.value[1] + ';';
  } // end of while
  console.log('===请求参数==uri==>' + uri + '==paramStr==>' + paramStr);
  return new Promise((resolve, reject) => {
    fetch(uri, init)
      .then(response => response.json())
      .then(data => {
        console.log('===请求成功===data====>' + JSON.stringify(data));
        Portal.remove(loadingKey);
        if (data) {
          if (data.errorCode === 0) {
            resolve(data.body);
          } else {
            if (data.errorCode === 100010 && data.errMsg) {
              // 卡密重复错误码
              reject(data.errMsg);
            } else {
              reject({
                status: -2,
                msg: data.errMsg ? data.errMsg : '业务加载异常!'
              });
              Toast.fail(data.errMsg ? data.errMsg : '抱歉,加载异常,请重试!');
            }
          }
        } // end of if
      })
      .catch(ex => {
        console.log('===请求失败===error====>' + JSON.stringify(ex));
        reject({ status: -1, msg: '网络连接错误!', error: ex });
        Toast.fail('抱歉,网络连接错误,请重试!');
        Portal.remove(loadingKey);
      });
  });
}
